﻿#region

using System.Collections.Concurrent;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Vin.Extension.Framework.Aop;
using Vin.Extension.Framework.Constants;
using Vin.Extension.Framework.Monitor.ServiceInterface;
using Vin.Extension.SqlSugar;
using Vin.Extension.SqlSugar.Utils;
using Vin.Tool.AspNetCore.Singleton;

#endregion

namespace Vin.Extension.Framework.Monitor.Filters;

public class OperateLogAttribute : VinLogAttribute
{
    public string Title { get; set; }

    public int BusinessType { get; set; }


    public OperateLogAttribute(string title, int businessType)
    {
        Title = title;
        BusinessType = businessType;
    }

    public OperateLogAttribute(string title, VinBusinessType businessType)
    {
        Title = title;
        BusinessType = (int)businessType;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var sysOperateLogService = VinApp.GetRequiredServiceByHttpContext<ISysOperateLogService>();
        var sqlSugarClient = VinApp.GetRequiredServiceByHttpContext<ISqlSugarClient>();

        #region 记录日志

        List<string> sqlList = new();
        if (sqlSugarClient is VinSqlSugarClient client)
        {
            client.VinAop.OnLogExecuting = (db, sql, pars) =>
            {
                sqlList.Add(VinSqlSugarUtilsMethods.GetAppendSql(sql, pars));
            };
        }

        #endregion
        
        var (httpContextInfo, costTime) = await GetResult(context, next);
        
        await sysOperateLogService.PreSaveAsync(Title, BusinessType, costTime, sqlList, httpContextInfo);
    }
}